package com.admin.controller;


import cn.hutool.core.io.FileUtil;
import com.admin.entity.Apk;
import com.admin.entity.Station;
import com.admin.entity.SystemApk;
import com.admin.service.IStationService;
import com.admin.service.ISystemApkService;
import com.admin.service.impl.SystemApkServiceImpl;
import com.aliyun.OssUpload;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author marisheng
 * @since 2019-11-21
 */
@RestController
@RequestMapping("/admin/system-apk")
public class SystemApkController {


    @Autowired
    private ISystemApkService systemApkService;

    @Autowired
    private IStationService stationService;

    @Value("${upload.tmp.dir}")
    private String tmp;

    @Value("${upload.dir}")
    private String upload;

    @Autowired
    private OssUpload ossUpload;


    /**
     * 查询系统apk升级包同时搜索应用名称
     *
     * @param page
     * @param limit
     * @param apkName
     * @return
     */
    @PostMapping("/SearchSystemApk")
    public ResponseBean SearchSystemApk(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, String apkName) {
        IPage result = systemApkService.SearchSystemApk(page, limit, apkName);
        return new ResponseBean(0, result.getTotal(), result.getRecords());
    }

    /**
     * 查询所有系统apk并分页
     *
     * @param page
     * @param limit
     * @param systemApkName
     * @return
     */
    @RequestMapping("/searchSystemApkWithPage")
    public ResponseBean searchSystemApkWithPage(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, String systemApkName) {
        IPage result = systemApkService.searchSystemApkWithPage(page, limit, systemApkName);
        return new ResponseBean(0, result.getTotal(), result.getRecords());
    }

    /**
     * 新增系统apk应用
     *
     * @param systemApk
     * @return
     */
    @RequestMapping(value = "/addSystemApk", method = RequestMethod.POST)
    public ResponseBean addSystemApk(SystemApk systemApk) {
        if (systemApkService.selectSystemApkMd5AndApkAdmin(systemApk.getSystemApkMd5()) != null) {
            return new ResponseBean(500, null, "文件已上传");
        }
        //得到当前时间
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime time = LocalDateTime.now();
        String localTime = df.format(time);
        LocalDateTime uploadTime = LocalDateTime.parse(localTime, df);
        systemApk.setSystemApkUploadTime(uploadTime);
        //截取得到文件名
        String oldPath = systemApk.getSystemApkUrl();
        int index = oldPath.lastIndexOf("\\");
        if (index == -1) {
            index = oldPath.lastIndexOf("/");
        }
        String newPath = oldPath.substring(index + 1);
        if ("是".equals(systemApk.getSystemApkStatus())) {
            systemApk.setSystemApkStatus("启用");
        } else {
            systemApk.setSystemApkStatus("禁用");
        }
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String path = "apk/launcher/" + today + "/" + newPath;
        systemApk.setSystemApkUrl("/upload/"+path);
        int insert = systemApkService.addSystemApk(systemApk);
        if (insert > 0) {
            //将apk应用文件从临时目录复制到正式目录
            FileUtil.copy(tmp + "/" + newPath, upload + path, true);
            File f = new File(upload + path);
            if (f.exists()) {
                ossUpload.upload("/upload/"+path,f );
            }
            return new ResponseBean(200, "新增成功", systemApk);
        }
        return new ResponseBean(500, "新增失败", "");
    }

    /**
     * 根据id修改系统apk
     *
     * @param systemApk
     * @return
     */
    @RequestMapping(value = "/updateSystemApkById", method = RequestMethod.POST)
    public ResponseBean updateSystemApkById(SystemApk systemApk) {
        if (systemApk == null) {
            return new ResponseBean(0, null, null);
        }


        if ("是".equals(systemApk.getSystemApkStatus())) {
            systemApk.setSystemApkStatus("启用");
        } else {
            systemApk.setSystemApkStatus("禁用");
        }

        //截取得到文件名
        String oldPath = systemApk.getSystemApkUrl();
        String newPath = null;
        String path = null;
        if (StringUtil.isNotNull(oldPath)) {
            int index = oldPath.lastIndexOf("\\");
            if (index == -1) {
                index = oldPath.lastIndexOf("/");
            }
            newPath = oldPath.substring(index + 1);
            String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            path = "apk/launcher/" + today + "/" + newPath;
            systemApk.setSystemApkUrl("/upload/"+path);

            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime time = LocalDateTime.now();
            String localTime = df.format(time);
            LocalDateTime uploadTime = LocalDateTime.parse(localTime, df);
            systemApk.setSystemApkUploadTime(uploadTime);
        } else {
            SystemApk tempApk = systemApkService.getById(systemApk.getSystemApkId());
            systemApk.setSystemApkUrl(tempApk.getSystemApkUrl());
            systemApk.setSystemApkMd5(tempApk.getSystemApkMd5());
        }

        if (StringUtil.isNotNull(path) && systemApkService.selectSystemApkMd5AndApkAdmin(systemApk.getSystemApkMd5()) != null) {
            return new ResponseBean(500, "文件已上传", "文件已上传");
        }

        boolean f = systemApkService.updateById(systemApk);
        if (f && StringUtil.isNotNull(path)) {
            //将apk应用文件从临时目录复制到正式目录
            FileUtil.copy(tmp + "/" + newPath, upload + path, true);
            File file = new File(upload + path);
            if (file.exists()) {
                ossUpload.upload("/upload/"+path,file);
            }
        }
        return new ResponseBean(200, "编辑成功", systemApk);
    }

    /**
     * 根据id删除系统apk
     *
     * @param systemApkId
     * @return
     */
    @RequestMapping(value = "deleteSystemAPKById", method = RequestMethod.POST)
    public ResponseBean deleteSystemAPKById(int systemApkId) {
        boolean f = systemApkService.removeById(systemApkId);
        int code = f ? 200 : 500;
        return new ResponseBean(code, null, null);
    }

    /**
     * 选择系统apk
     *
     * @param systemApkId 系统APK编号
     * @param stationId   站点编号
     * @return
     */
    @RequestMapping("/selectLauncher")
    public ResponseBean selectLauncher(int systemApkId, int stationId) {
        Station station = stationService.getById(stationId);
        if (station == null) {
            return new ResponseBean(500, "站点信息获取失败", null);
        }

        SystemApk systemApk = systemApkService.getById(systemApkId);
        if (systemApk == null) {
            return new ResponseBean(500, "系统APK信息获取失败", null);
        }

        station.setStationSystemUpdate(systemApkId);
        stationService.updateById(station);

        return new ResponseBean(200, "操作成功", null);

    }

    @RequestMapping("/getLauncherVer")
    public ResponseBean getLauncherVer(int stationId) {
        Station station = stationService.getById(stationId);
        if (station == null) {
            return new ResponseBean(500, "站点信息获取失败", null);
        }
        Integer ver = station.getStationSystemUpdate();
        if (ver == null) {
            return new ResponseBean(500, "获取版本信息失败", null);
        }

        SystemApk systemApk = systemApkService.getById(ver);
        if (systemApk == null) {
            return new ResponseBean(500, "系统APK对象信息获取失败", null);
        }

        String version = systemApk.getSystemApkVesion();
        if (StringUtil.isNull(version)) {
            return new ResponseBean(500, "系统APK信息获取失败", null);
        }

        return new ResponseBean(200, "获取版本信息成功", version);
    }


}
